package com.company.finance.ddd.domain.core.voucher.rule;

import com.company.finance.ddd.domain.core.voucher.enums.VoucherSubjectEnum;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.ToString;

import java.lang.reflect.Field;

/**
 * 本类是单据明细生成凭证明细的规则类
 * @author wanglei
 */
@Builder
@Getter
@ToString
public class BillItemRule {

    private final VoucherSubjectEnum debitSubject;
    private final DigestRule debitDigestRule;
    private final VoucherSubjectEnum creditSubject;
    private final DigestRule creditDigestRule;

    private BillItemRule(VoucherSubjectEnum debitSubject, DigestRule debitDigestRule, VoucherSubjectEnum creditSubject,
                         DigestRule creditDigestRule) {
        this.debitSubject = debitSubject;
        this.debitDigestRule = debitDigestRule;
        this.creditSubject = creditSubject;
        this.creditDigestRule = creditDigestRule;
    }

    @Data
    @Builder
    public static class DigestRule {
        VoucherDigestSetter digestSetter;
        String layout;
        String[] placeholder;
        Object layoutSetter;

        public DigestRule setDigestSetter(VoucherDigestSetter digestSetter) {
            this.digestSetter = digestSetter;
            return this;
        }

        public String buildDigest() {
            String value;
            for (String ph : placeholder) {
                try {
                    Field field = digestSetter.getClass().getDeclaredField(ph);
                    field.setAccessible(true);
                    value = field.get(digestSetter).toString();
                } catch (NoSuchFieldException | IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
                layout = layout.replace(ph, value);
            }
            return layout;
        }
    }
}
